<?php
require_once 'Croese/Google/Chart/Encoding.php';
/**
 * http://code.google.com/apis/chart/#text
 * Text encoding
 * -------------
 * 
 * Specify text encoding with
 * 
 * chd=t:<chart data string>
 * 
 * Where <chart data string> consists of positive floating point numbers from 
 * zero (0.0) to 100.0, minus one (-1), and the pipe character (|) as a 
 * separator.
 * 
 * Note:
 * - Zero (0.0) = 0, 1.0 = 1 and so on up to 100.0 = 100.
 * - Specify a missing value with minus one (-1).
 * - If you have more than one set of data, separate each set with a pipe 
 *   character (|).
 * 
 * For example: chd=t:10.0,58.0,95.0|30.0,8.0,63.0
 *
 */
class Croese_Google_Chart_Encoding_Text implements Croese_Google_Chart_Encoding
{

	const VALUE_MIN = 0.0;
	const VALUE_MAX = 100.0;
	const VALUE_MISSING = -1; 	
	
	/**
	 * Met deze functie encoden we de data op de Text manier.
	 *
	 * @param array $data
	 */
	public function encode($data)
	{
		$values = array();
		if(is_array($data) && !empty($data))
		{
			foreach ($data as $dataElement)
			{
				// multiple datasets
				if (is_array($dataElement))
				{
					$dataSet = $dataElement;
					foreach ($dataSet as $dataElem)
					{
						$dataElem = $this->_validateElement($dataElem);		
					}
				}
				else
				{
					$dataElement = $this->_validateElement($dataElement);
					$values[] = $dataElement;	
				}
			}
			return 'chd=t:' . implode(',', $values);
		}
		else
		{
			throw new Exception('Geen data opgegeven');
			return '';
		}
	}
	
	/**
	 * Valideert de data. Wanneer de data niet valide is geven we een
	 * 'missing value' terug
	 *
	 * @param unknown_type $element
	 * @return float|int
	 */
	private function _validateElement($element)
	{
		if(is_float((float)$element) || is_int((int)$element))
		{
			if($element >= self::VALUE_MIN && $element <= self::VALUE_MAX)
			{
				return $element;	
			}
			else
			{
				throw new Exception(sprintf("Waarde '%s' moet mag niet kleiner zijn dan 0.0 en niet groter dan 100.0", $element));
				return self::MISSING_VALUE;
			}
		}
		else
		{
			throw new Exception(sprintf("Waarde '%s' moet wel een float of int zijn", $element));
			return self::MISSING_VALUE;
		}
	}
}